﻿using System;
using System.IO;
using System.Windows.Forms;
using RSuite.Services;
using System.Diagnostics;

namespace RSuite.R2.Services
{
    public class WebService : WebServiceBase
    {
        protected override object Process(string method, dynamic parameters)
        {
            switch (method)
            {
                case "open":
                    return this.Open(parameters);
                case "save":
                    return this.Save(parameters["id"], parameters["review"]);
                default:
                    return null;
            }
        }

        private object Open(string id)
        {
            var path = this.GetReviewPath(id);
            if (!File.Exists(path))
            {
                return new
                {
                    status = 1,
                    message = "Id not found"
                };
            }
            else
            {
                return new
                {
                    id = id,
                    review = File.ReadAllText(path)
                };
            }
        }

        private object Save(string id, string data)
        {
            if (string.IsNullOrEmpty(id))
            {
                id = string.Format("{0:yyyyMMddHHmmss}", DateTime.Now);
            }
            var filename = this.GetReviewPath(id);
            if (!Directory.Exists(Path.GetDirectoryName(filename)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filename));
            }

            File.WriteAllText(this.GetReviewPath(id), data);
            return id;
        }

        private string GetReviewPath(string id)
        {
            var appPath = Path.GetDirectoryName(Application.ExecutablePath);
            return Path.Combine(appPath, "Reviews", string.Format("{0}.rvw", id));
        }
    }
}